<!--
 * @Description: socket
 * @Author: rendc
 * @Date: 2021-09-15 12:07:51
 * @LastEditors: rendc
 * @LastEditTime: 2021-09-15 14:07:00
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>socket</title>
  <script src="../js/jquery.js"></script>
</head>

<body>
  ip:<input name="ip" type="text" value="47.94.46.113"><br>
  port: <input name="port" type="text" value="8888"><br>
  path: <input name="path" type="text" value="/imserver/1"><br>
  <button id="open_btn">打开连接</button>
  <button id="close_btn">关闭连接</button>
  <div id="msg"></div>
</body>
<script>
  var socket;
  $(function () {
    $("#open_btn").click(openSocket);
    $("#close_btn").click(closeSocket);
  })

  function closeSocket() {
    socket.close();
  }

  function openSocket() {
    if (typeof (WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
    } else {
      // 如果socket存在先关闭，并且设置为空，方便重新连接
      if (socket != null) {
        socket.close();
        socket = null;
      }
      // socket协议 ：ws://ip:port/path
      var ip = $("input[name=ip]").val();
      var port = $("input[name=port]").val();
      var path = $("input[name=path]").val();
      if (!(ip && port && path)) {
        alert("请填写连接信息");
        return false;
      }

      socket = new WebSocket("ws://" + ip + ":" + port + path);
      //打开事件
      socket.onopen = function () {
        $("#msg").text("websocket已打开");
      };
      //获得消息事件
      socket.onmessage = function (msg) {
        $("#msg").text("接收到后端消息:" + msg.data);
      };
      //关闭事件
      socket.onclose = function () {
        $("#msg").text("websocket已关闭");
      };
      //发生了错误事件
      socket.onerror = function () {
        $("#msg").text("websocket发生了错误");
      }
    }
  }
</script>

</html>